package org.gcb.core.ui.dnd;

import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.InputEvent;
import java.io.IOException;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.TransferHandler;
import org.gcb.core.model.Item;
import org.gcb.core.sandbox.JSlot;
import org.openide.util.Exceptions;

/**
 *
 * @author Jason
 */
public class ItemTransferHandler extends TransferHandler{

    @Override
    public boolean canImport(TransferSupport support) {
	if (!support.isDrop()) {
	    return false;	    //only supporting drag and drop - no cut/copy/paste
	}
	if (!support.isDataFlavorSupported(Item.ITEM_DATA_FLAVOR)) {
	    return false;	    //only suporting org.gcb.core.model.Item transfers
	}

        return support.isDataFlavorSupported(Item.ITEM_DATA_FLAVOR);
    }

    @Override
    protected Transferable createTransferable(JComponent c) {
	Transferable trans = super.createTransferable(c);
        return trans;
    }

    @Override
    public int getSourceActions(JComponent c) {
	return MOVE;
    }

    @Override
    public boolean importData(TransferSupport support) {
	if (!canImport(support)) {
	    return false;
	}
	JComponent jComponent = (JComponent) support.getComponent();
	JSlot jSlot = (JSlot) jComponent;
	Transferable t = support.getTransferable();
	Item i = null;
	try {
	    i = Item.class.cast(t.getTransferData(Item.ITEM_DATA_FLAVOR));
	    jSlot.getModel().setItem(i);
	} catch (UnsupportedFlavorException ex) {
	    Exceptions.printStackTrace(ex);
	} catch (IOException ex) {
	    Exceptions.printStackTrace(ex);
	}
	if (i==null) {
	    return false;
	}
        return true;
    }

    @Override
    public void exportAsDrag(JComponent comp, InputEvent e, int action) {
        super.exportAsDrag(comp, e, action);
    }

    @Override
    protected void exportDone(JComponent source, Transferable data, int action) {
	//remove from either slot or bag, depending on source
	JComponent src = source;
	Transferable t = data;
	int act = action;
        super.exportDone(source, data, action);
    }

    @Override
    public Icon getVisualRepresentation(Transferable t) {
	try {
	    return Item.class.cast(t.getTransferData(Item.ITEM_DATA_FLAVOR)).getIcon();
	} catch (UnsupportedFlavorException ex) {
	    Exceptions.printStackTrace(ex);
	} catch (IOException ex) {
	    Exceptions.printStackTrace(ex);
	}
	return super.getVisualRepresentation(t);
    }

    @Override
    public boolean importData(JComponent comp, Transferable t) {
        return super.importData(comp, t);
    }

}
